import numpy as np  
import sympy as sp
import matplotlib.pyplot as plt  
import math
 


def readfile(filename):
    with open(filename, "r") as file:  
        lines = file.readlines()  
    rc = []    
    for line in lines:  
        nums = line.strip().split(" ")  
        nums = [float(num) for num in nums]  
        rc.append(nums) 
    return rc

def file_line(filename):
    with open(filename, 'r') as file:  
        line_count = sum(1 for line in file)
    return line_count

def my_plot_a(filename):  
    line_count = file_line(filename)  
    rc = readfile(filename)  
  
    xx = rc[0]  # 获取 x 值  
    fx = rc[1:line_count-2]  # 获取函数值  
    errors = rc[line_count-1] #获取误差值
    knot_num = []
    for j in range(line_count - 2):  
        plt.plot(xx, rc[j+1], label=f"N={2**j * 5 + 1}",linewidth=0.9)  # 绘制曲线并添加对应的图例标签  
    x = np.linspace(-1, 1, 501)  
    real_fx =1/(1+25*x*x)
    plt.plot(xx,real_fx,label = "1/(1+25x^2)",linestyle='--')
    plt.xlabel('x')    
    plt.ylabel('y')    
    plt.title('Function Plot')    
    plt.legend()  # 显示图例  
    plt.show()   

    
    for k in range(line_count-2):
        knot_num.append((2**k*+1))
        errors[k] = (math.log(errors[k]))

    plt.plot(knot_num,errors,label = "max_error")
    plt.xlabel('num of subintvals N')    
    plt.ylabel('ln(errors)')    
    plt.title('errors with num of subintvals')    
    plt.legend()  # 显示图例  
    plt.show()

def my_plot_c(filename):
    line_count = file_line(filename)
    rc = readfile(filename)

    xx = rc[0]
    fx = rc[1:]

    x = np.linspace(-5, 5, 501)  
    real_fx =1/(1+x*x)
    plt.plot(x,real_fx,label = "1/(1+x^2)",linestyle='--')

    plt.plot(xx , fx[0] ,label = "cubic by complete ")
    plt.plot(xx , fx[1] ,label = "quadratic ")

    plt.xlabel('x')  
    plt.ylabel('y')  
    plt.title('Function Plot')  
    plt.legend()  
    plt.show()  



def my_plot_e(filename):

    re = readfile(filename)
    xx = re[0]
    yx = re[1]

    knot_x = re[2]
    knot_y = re[3]


    plt.plot(xx , yx ,label = "heart")
    plt.scatter(knot_x,knot_y,color = "red",s=2)

    plt.xlabel('x')  
    plt.ylabel('y')  
    plt.title('Heart')  
    plt.legend()  
    plt.show()    
  

my_plot_a("/home/chen/Project/na/Project/src/A.txt")  
my_plot_c("/home/chen/Project/na/Project/src/C.txt")  
my_plot_e("/home/chen/Project/na/Project/src/E.txt")  
